package org.springblade.modules.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.google.common.collect.Lists;
import com.aliyun.dyvmsapi20170525.models.IvrCallRequest;
import com.aliyun.dyvmsapi20170525.models.IvrCallResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lark.oapi.Client;
import com.lark.oapi.core.response.RawResponse;
import com.lark.oapi.core.token.AccessTokenType;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import com.sida.voice.service.VoiceClient;
import com.sida.voice.service.VoiceTemplate;
import com.uber.h3core.H3Core;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springblade.common.config.FeiShuConfiguration;
import org.springblade.common.constant.MaintenanceSmsConstant;
import org.springblade.common.enums.FeishuClientEnum;
import org.springblade.common.mq.MqMessageService;
import org.springblade.common.utils.CDNUtil;
import org.springblade.common.utils.CookieUtil;
import org.springblade.common.utils.ivrcall.IvrCallUtil;
import org.springblade.common.utils.feishu.ClientSecure;
import org.springblade.common.utils.feishu.FeiShuUtil;
import org.springblade.common.utils.message.MessageCenterUtils;
import org.springblade.common.utils.message.domain.MessageParam;
import org.springblade.common.utils.message.domain.SendRequest;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.sms.model.SmsResponse;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.*;
import org.springblade.modules.admin.dto.rescue.RescueTrappedNoticeDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.entity.feishu.*;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.RescueArriveEnum;
import org.springblade.modules.admin.enums.StatusEnum;
import org.springblade.modules.admin.event.RescueTrappedNoticeEvent;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.service.feishu.ILarkFaultRiskMessageService;
import org.springblade.modules.admin.task.CertJob;
import org.springblade.modules.admin.task.OrderScoreJob;
import org.springblade.modules.admin.task.PlanContentJob;
import org.springblade.modules.admin.task.feishu.LarkRescueAndFaultIndexJob;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.admin.utils.GenerateElevatorNumService;
import org.springblade.modules.admin.utils.MailUtil;
import org.springblade.modules.admin.utils.TranslationUtil;
import org.springblade.modules.admin.vo.TestVO;
import org.springblade.modules.admin.vo.plan.wx.WxYjSendMsgVo;
import org.springblade.modules.notice.core.event.NoticeEvent;
import org.springblade.modules.notice.dto.NoticeTaskParam;
import org.springblade.modules.notice.enums.BusinessType;
import org.springblade.modules.notice.enums.TriggerConditionEnum;
import org.springblade.modules.notice.enums.TriggerNodeEnum;
import org.springblade.modules.resource.utils.SmsUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Jackey
 * @date 2021年08月25日 8:59 上午
 */
@Slf4j
@RestController
@RequestMapping("/test/")
public class TestController {

	//	@Autowired
//	DelayedSend delayedSend;
	@Autowired
	private Environment environment;
	@Autowired
	private BuildingContractService buildingContractService;

	@Resource
	private LiftElevatorService liftElevatorService;

	@Autowired
	private MailUtil mailUtil;

	@Autowired
	private IBuildingContractPlusService buildingContractPlusService;

	@Autowired
	private UserWeixinService userWeixinService;

	@Autowired
	private VoiceClient voiceClient;

	@Autowired
	private WeChatDialogueService weChatDialogueService;

	@Autowired
	private AsyncUtils asyncUtils;
	@Autowired
	private GenerateElevatorNumService elevatorNumService;

	@Autowired
	private MqMessageService mqMessageService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private CompanyElevatorService companyElevatorService;

	@Autowired
	private OrderScoreJob orderScoreJob;
	@Autowired
	private IUserService userService;
	@Autowired
	private FeiShuUtil feiShuUtil;
	@Autowired
	private IMaintainPlanContentExtService planContentExtService;

	@Autowired
	private FeiShuConfiguration feiShuConfiguration;

	@Autowired
	private CertJob certJob;

	@Autowired
	private PlanContentJob planContentJob;

	@Autowired
	private MaintainPlanUserDayCountService planUserDayCountService;
	@Autowired
	private IElevatorRepeatFaultLogService elevatorRepeatFaultLogService;

	@Resource
	private ElevatorService elevatorService;

	@Autowired
	private IMaintainPlanTemplateService planTemplateService;

	@Autowired
	private MaintainPartsWorkService partsWorkService;
	@Autowired
	private IElevatorWxNumberService elevatorWxNumberService;
	@Autowired
	private IElevatorWxNumberStatisticService elevatorWxNumberStatisticService;
	@Autowired
	private IMaintainPlanContentService maintainPlanContentService;

	@Autowired
	private H3IndexService h3IndexService;
	@Autowired
	private BuildingService buildingService;
	@Autowired
	private ILarkFaultRiskMessageService larkFaultRiskMessageService;
	@Autowired
	private LarkRescueAndFaultIndexJob larkRescueAndFaultIndexJob;
	@Autowired
	private IvrCallUtil ivrCallUtil;

	private static final String FS_E_S_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/5757acc0-e716-4b85-8ed1-69d5f2313acc";
	private static final String FS_E_S_WEBHOOK_PROD = "https://open.feishu.cn/open-apis/bot/v2/hook/ec158f10-29c7-4bbd-a61e-4638ec801e59";


	@GetMapping("/h3_index")
	public R<Boolean> h3Index() throws IOException {
		List<Building> list = buildingService.listByH3Index();
		for (Building building : list) {
			H3Index h3Index = new H3Index();
			h3Index.setBuildingId(building.getId());

			for (int res = 5; res <= 10; res++) {
				H3Core h3Core = H3Core.newInstance();
				String index = h3Core.latLngToCellAddress(building.getLatitude().doubleValue(), building.getLongitude().doubleValue(), res);
				switch (res) {
					case 5:
						h3Index.setRes5Index(index);
						break;
					case 6:
						h3Index.setRes6Index(index);
						break;
					case 7:
						h3Index.setRes7Index(index);
						break;
					case 8:
						h3Index.setRes8Index(index);
						break;
					case 9:
						h3Index.setRes9Index(index);
						break;
					case 10:
						h3Index.setRes10Index(index);
						break;
					default:
						break;
				}
			}

			h3IndexService.save(h3Index);
		}
		return R.status(true);
	}

	@GetMapping("/translation")
	public R<Boolean> testTranslation(@RequestParam String string, @RequestParam String  language) {
		// 添加新的翻译映射
		TranslationUtil.addTranslation(string, language);
		return R.status( true);
	}

	@GetMapping("/zccTest")
	public R<String> zccTest(Long elevatorId) {
		List<ElevatorWxNumber> numbers = elevatorWxNumberService.list(Wrappers.<ElevatorWxNumber>lambdaQuery().eq(ElevatorWxNumber::getStatus, StatusEnum.ENABLE.getId()));
		List<Integer> days = numbers.stream().map(ElevatorWxNumber::getDays).distinct().collect(Collectors.toList());
		Integer max = days.stream().reduce(days.get(0), Integer::max) * -1;
		List<MaintainPlanContent> contentList = maintainPlanContentService.list(Wrappers.<MaintainPlanContent>lambdaQuery().eq(MaintainPlanContent::getTypeStatus, MaintainPlanContentEnum.MAINTAIN_WX.getId()).eq(MaintainPlanContent::getElevatorId, elevatorId).between(MaintainPlanContent::getCreateTime, DateUtil.offsetDay(new Date(), max), new Date()));
		for (ElevatorWxNumber elevatorWxNumber : numbers) {
			Date offsetDay = DateUtil.offsetDay(new Date(), elevatorWxNumber.getDays() * -1);
			Integer counts = 1;
			for (MaintainPlanContent maintainPlanContent : contentList) {
				if (maintainPlanContent.getCreateTime().after(offsetDay)) {
					counts = counts + 1;
				}
			}
			if (counts >= elevatorWxNumber.getRepetitionCounts()) {
				ElevatorWxNumberStatistic elevatorWxNumberStatistic = new ElevatorWxNumberStatistic();
				elevatorWxNumberStatistic.setElevatorId(elevatorId);
				elevatorWxNumberStatistic.setWxNumberId(elevatorWxNumber.getId());
				elevatorWxNumberStatistic.setWxNumberDesc(elevatorWxNumber.getTypeDesc());
				elevatorWxNumberStatisticService.save(elevatorWxNumberStatistic);
			}
		}
		return null;
	}


	@TenantIgnore
	@GetMapping("/send/fs/elevator/stop")
	public R<Object> sendFs(Integer msgType, Integer contentType) {
		ElevatorStopPlanSimpleDTO simpleDTO = new ElevatorStopPlanSimpleDTO();
		FeiShuElevatorStopCertContentTemplate template = new FeiShuElevatorStopCertContentTemplate(111L, msgType, contentType, 4, simpleDTO);
		Map<String, Object> map = new HashMap<>();
		map.put("msg_type", "interactive");
		map.put("card", template.getCertContentTemplate());
		return R.data(HttpUtil.post(FS_E_S_WEBHOOK_PROD, JSONObject.toJSONString(map)));
	}

	@TenantIgnore
	@GetMapping("/update/mal/relation/parts")
	public R<Boolean> updateMalRelationParts() {
		return R.data(partsWorkService.updateMalRelationParts());
	}

	@TenantIgnore
	@GetMapping("/add/plan/template")
	public R<Boolean> addPlanTemplate(Long elevatorUseType, Long templateId, String tenantId) {
		return R.data(planTemplateService.addPlanTemplate(elevatorUseType, templateId, tenantId));
	}

	@TenantIgnore
	@GetMapping("/repeat/fault/elevator")
	public R<Boolean> repeatFaultElevator() {
		List<String> tenantList = new ArrayList<>();
		tenantList.add("592800");
		elevatorRepeatFaultLogService.selectRepeatFaultElevator(tenantList);
		return R.data(Boolean.TRUE);
	}

	@TenantIgnore
	@GetMapping("/repeat/fault/elevator/plan")
	public R<Boolean> selectRepeatFaultElevatorPlan() {
		List<String> tenantList = new ArrayList<>();
		tenantList.add("592800");
		elevatorRepeatFaultLogService.selectRepeatFaultElevatorPlan(tenantList);
		return R.data(Boolean.TRUE);
	}

	@TenantIgnore
	@GetMapping("/elevator/maintain/day/count")
	public R<?> elevatorMaintainDayCount() {
		elevatorService.updateElevatorMaintainStatusDay();
		return R.data(null);
	}

	@TenantIgnore
	@GetMapping("/plan/user/day/count")
	public R<?> planUserDayCount() {
		planUserDayCountService.updatePlanUserDayCount(MaintainPlanContentEnum.MAINTAIN_BY.getId());
		return R.data(null);
	}

	@TenantIgnore
	@GetMapping("/user/wx")
	public R<?> testUserWx() {
		userWeixinService.updateUserSubscribe();
		return R.data(null);
	}

	@TenantIgnore
	@GetMapping("/user/init/zhCode")
	public R<?> testUserInitZhCode() {
		List<User> list = userService.list();
		for (User user : list) {
			if (Func.isNotBlank(user.getRealName())) {
				final String firstLetter = PinyinUtil.getFirstLetter(user.getRealName(), "");
				user.setZhCode(firstLetter.toLowerCase());
			}
		}
		final List<List<User>> saveList = com.google.common.collect.Lists.partition(list, 20);
		for (List<User> list1 : saveList) {
			userService.updateBatchById(list1);
		}
		return R.data("初始化数据成功");
	}

	@GetMapping("/random")
	public R<String> randomNum() {
		return R.data(elevatorNumService.generateElevatorNum(1384678625908932610L));
	}

	@GetMapping("/remove")
	public R<Boolean> remove(String elevatorNum) {
		return R.status(elevatorNumService.removeElevatorNum(elevatorNum));
	}

	@GetMapping("cdn")
	public R<Map<String, ?>> refreshCDN() throws Exception {
		Map<String, ?> refresh = CDNUtil.refresh();
		return R.data(refresh);
	}

	@TenantIgnore
	@GetMapping("/init/plan/commit")
	public R<Boolean> initPlanCommit() {
		return R.data(planContentExtService.initPlanCommit());
	}

	/**
	 * 发送延迟消息
	 *
	 * @param
	 * @return
	 */
//	@GetMapping("delayed_send")
//	public R<String> delayedSend(String privateNum) {
//
//		System.out.println(privateNum);
//
//		//发送延时队列消息(当前时间毫秒值+需要延迟的毫秒值)
//		long date = System.currentTimeMillis() + 10000;
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("privateNum", "10000220000033000002");
//		jsonObject.put("checkType", ElevatorAuditEnum.AUDIT.getCode());
//		jsonObject.put("sendTime", "2021-01-01");
//		delayedSend.sendDelayed(date, JSONObject.toJSONString(jsonObject));
//
//		return R.data(privateNum);
//	}
	@GetMapping("hehe")
	public void testEnv() {
		String[] activeProfiles = environment.getActiveProfiles();
		System.out.println(activeProfiles[0]);

		if ("dev".equals(activeProfiles[0])) {
			List<String> collect = buildingContractService.list().stream().map(BuildingContract::getContractId).collect(Collectors.toList());
			List<String> contractList = new ArrayList<>();
			for (String s : collect) {
				List<String> stringList = StrUtil.split(s, ',');
				contractList.addAll(stringList);
			}

			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("j_tenantid", 2);
			paramMap.put("j_username", "金明浩");
			paramMap.put("j_password", "yinhe123");

			Map<String, String> headerMap = new HashMap<>();
			headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
			headerMap.put("Content-Type", "application/x-www-form-urlencoded");
			headerMap.put("Host", "14.215.246.98:8888");
			headerMap.put("Origin", "http://14.215.246.98:8888");
			headerMap.put("Referer", "http://14.215.246.98:8888/security/html/login.jsp");
			headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36");

			HttpResponse httpResponse = HttpRequest.post("http://14.215.246.98:8888/j_spring_security_check").form(paramMap).addHeaders(headerMap)
				.execute();
			Map<String, List<String>> headers = httpResponse.headers();
			String nCookieString = headers.get("Set-Cookie").get(0);
			String cookieString = StrUtil.split(nCookieString, ';').get(0);
			headerMap.put("Cookie", "sysbaseVersion=11.9.0; jgsize_maintainContractList=10000; " + cookieString);
			HttpResponse finalResponse = HttpRequest.get("http://14.215.246.98:8888/index.jsp").addHeaders(headerMap)
				.execute();
			String body = HttpRequest.get("http://14.215.246.98:8888/maintain/contractAction!findList.action?state=1&from=maintain&random=0.2112853273481099&_search=true&nd=1638253734172&rows=10000&page=1&sidx=item_id&sord=asc")
				.addHeaders(headerMap)
				.execute().body();
			cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
			JSONArray dataArray = JSONUtil.parseArray(jsonObject.get("data"));

			if (StrUtil.isNotEmpty(body)) {

				buildingContractPlusService.syncData(body);
				return;
			}


			List<String> idList = dataArray.stream().map(o -> {
				cn.hutool.json.JSONObject data = JSONUtil.parseObj(o);
				return data.get("id").toString();
			}).collect(Collectors.toList());

			//差集
			idList.removeAll(contractList);
			List<Map<String, String>> mapList = new ArrayList<>();
			if (idList.size() > 0) {
				for (String s : idList) {
					String data = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=" + s + "&state=1&from=maintain&random=0.5479617521381546&_search=true&nd=1638257480883&rows=20&page=1&sidx=item_id&sord=asc")
						.addHeaders(headerMap)
						.execute().body();
					cn.hutool.json.JSONObject object = JSONUtil.parseObj(data);
					if (JSONUtil.parseArray(object.get("data")).size() > 0) {
						cn.hutool.json.JSONObject detail = JSONUtil.parseObj(JSONUtil.parseArray(object.get("data")).get(0));
						Map<String, String> map = new HashMap<>();
						map.put("contractId", s);
						map.put("contractNo", (String) detail.get("contractNo"));
						mapList.add(map);
					}

				}
				mailUtil.sendSimpleMail("137177384@qq.com", "日常", mapList.toString());
			}

		}

	}

	@GetMapping("xixi")
	public void test1() {
		String[] activeProfiles = environment.getActiveProfiles();
		System.out.println(activeProfiles[0]);

		if ("dev".equals(activeProfiles[0])) {
			List<String> collect = liftElevatorService.list().stream().map(LiftElevator::getLId).collect(Collectors.toList());

			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("j_tenantid", 2);
			paramMap.put("j_username", "金明浩");
			paramMap.put("j_password", "yinhe123");

			Map<String, String> headerMap = new HashMap<>();
			headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
			headerMap.put("Content-Type", "application/x-www-form-urlencoded");
			headerMap.put("Host", "14.215.246.98:8888");
			headerMap.put("Origin", "http://14.215.246.98:8888");
			headerMap.put("Referer", "http://14.215.246.98:8888/security/html/login.jsp");
			headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36");

			HttpResponse httpResponse = HttpRequest.post("http://14.215.246.98:8888/j_spring_security_check").form(paramMap).addHeaders(headerMap)
				.execute();
			Map<String, List<String>> headers = httpResponse.headers();
			String nCookieString = headers.get("Set-Cookie").get(0);
			String cookieString = StrUtil.split(nCookieString, ';').get(0);
			headerMap.put("Cookie", "sysbaseVersion=11.9.0; jgsize_maintainContractList=10000; " + cookieString);
			HttpResponse finalResponse = HttpRequest.get("http://14.215.246.98:8888/index.jsp").addHeaders(headerMap)
				.execute();


			String body = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=&state=1&from=contract&random=0.6129245027313386&_search=true&nd=1638324752218&rows=10000&page=1&sidx=item_id&sord=asc")
				.addHeaders(headerMap)
				.execute().body();
			cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
			JSONArray dataArray = JSONUtil.parseArray(jsonObject.get("data"));

			List<String> idList = dataArray.stream().map(o -> {
				cn.hutool.json.JSONObject data = JSONUtil.parseObj(o);
				return data.get("liftId").toString();
			}).collect(Collectors.toList());

			//差集
			idList.removeAll(collect);
			List<Map<String, String>> mapList = new ArrayList<>();
			if (idList.size() > 0) {
				for (String s : idList) {
					String data = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=&state=1&from=contract&random=0.6129245027313386&_search=true&nd=1638325189971&rows=20&page=1&sidx=item_id&sord=asc&liftId=" + s)
						.addHeaders(headerMap)
						.execute().body();
					cn.hutool.json.JSONObject object = JSONUtil.parseObj(data);
					cn.hutool.json.JSONObject detail = JSONUtil.parseObj(JSONUtil.parseArray(object.get("data")).get(0));
					Map<String, String> map = new HashMap<>(3);
					map.put("liftId", s);
					map.put("liftNo", (String) detail.get("liftNo"));
					map.put("liftIDNo", (String) detail.get("liftIDNo"));
					mapList.add(map);
				}
				mailUtil.sendSimpleMail("137177384@qq.com", "LiftCore [电梯] 有新数据 [增加]", mapList.toString());
			}
		}
	}

	@PostMapping("/send/note/msg")
	public R<?> sendNoteMsg(@RequestBody NotePushDTO pushDTO) {
		//发送短信
		HashMap<String, String> smsMap = new HashMap<>(2);
		smsMap.put("place", "test");
		asyncUtils.sendSms(MaintenanceSmsConstant.ESTATE_RESCUE, smsMap, pushDTO.getPhone());
		return R.status(Boolean.TRUE);
	}


	@GetMapping("testSendPhone")
	@ApiOperation("测试短信和语音")
	public R<Boolean> testSendPhone(String phone) {
		Map<String, String> smsParam = new HashMap<>(2);
		smsParam.put("location", "测试项目" + "测试梯");
		smsParam.put("type", "待发货");
		smsParam.put("module", "梯无忧后台配件发货");
		final SmsResponse smsResponse = SmsUtil.sendMessage(MaintenanceSmsConstant.PARTS_MESSAGE, BladeConstant.ADMIN_TENANT_ID, smsParam, phone);
		JSON.toJSONString(smsResponse);
		return R.status(Boolean.TRUE);
	}


	@GetMapping("testSendWeixin")
	@ApiOperation("测试语音播报")
	public R<Boolean> testSendWeixin(String phone) {


		Map<String, String> phoneMap = new HashMap<>(2);
		phoneMap.put("place", "测试项目测试梯");
		phoneMap.put("location", "梯无忧后台配件调度");
		VoiceTemplate voiceTemplate = new VoiceTemplate();
		voiceTemplate.setTemplateCode("TTS_285155051");
		voiceTemplate.setTemplateParam(phoneMap);
		voiceTemplate.setPhoneNumber(phone);
		asyncUtils.sendPhone(voiceTemplate);

		return null;
	}

	@PostMapping("test/wx/demo")
	@ApiOperation("测试企业微信")
	public Map<String, Object> testWxDemo(@RequestBody TestDTO dto) {
		log.info("======================== 参数：{} =======================", JSON.toJSONString(dto));
		List<TestVO> list = new ArrayList<>();
		TestVO testVO = new TestVO();
		testVO.setType(4);
		testVO.setUrl("https://www.baidu.com");
		testVO.setDescription("进行中");
		testVO.setThumbnailUrl("http://image.xkboke.com/aibotk/public/gyLNbz97X65WqP27_v2-c6c2957f5a3eefa2e8ec22cfcf590116_xl.jpeg");
		testVO.setTitle("优雅会所电梯维保实时状态");
		list.add(testVO);

		Map<String, Object> map = new HashMap<>();
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", list);
		return map;
	}

	@PostMapping("test/rescueTaskMessage")
	@ApiOperation("紧急呼叫消息推送")
	public R rescueTaskMessage(@RequestBody RescueNoticeCreateDTO noticeCreate) {
		mqMessageService.sendRescueTaskMessage(JSONUtil.toJsonStr(noticeCreate));
		return R.status(true);
	}

	/**
	 * 爬取维保数据
	 *
	 * @return
	 */
	@GetMapping("spider")
	public R<Boolean> spider() {
//		List<Company> list = companyService.list(new LambdaQueryWrapper<Company>().isNotNull(Company::getContent));

		String template = "http://wsbj2.gdsei.org.cn:8078/seimis/SbglAction.do?method=select_submit&ec_i=ec&eti=&eti_p=&ec_efn=&ec_ev=&ec_crd=100000&ec_f_a=&ec_p=1&ec_s_EQULOGCODE=&ec_s_EQUIPNAME=&ec_s_USECARNO=&ec_s_EQUORGNO=&ec_s_USEORGNAME=&ec_s_DNAME=&ec_s_EQULOCARECOD=&ec_s_PRONO=&ec_s_INSREPORTNO=&ec_s_NINSPDATE=&ec_s_INSRESULT=&ec_s_OYINSREPORTNO=&ec_s_OYNINSPDATE=&ec_s_OYINSRESULT=&ec_s_PRESOYINSREPORTNO=&ec_s_PRESNDATE=&ec_s_PRESRESULT=&ec_s_USSTATUS=&ec_s_LOGINSTATE=&LOGINSTATE=&USSTATUS=&type=&BUIORGNAME=&areacodecontent1=440000&EQUIPNAME=&areacodecontent2=&1704183545096=&EQUIPMODEL=&USECARNO=&PRONO=&STACHEORGUNICODE=&USEORGSYSNO=&EQUORGNO=&EQULOCARECOD=&JYJL_PARA=&USEORGNAME=&EQUCLACODE=&EQULOGCODE=&MAIORGNAME=&PORGAONAME=&method=select_submit&method=select_submit&ec_totalpages=1&ec_totalrows=&ec_f_radio=&ec_f_%E5%BA%8F%E5%8F%B7=&ec_f_EQULOGCODE=&ec_f_EQUIPNAME=&ec_f_USECARNO=&ec_f_EQUORGNO=&ec_f_USEORGNAME=&ec_f_DNAME=&ec_f_EQULOCARECOD=&ec_f_PRONO=&ec_f_INSREPORTNO=&ec_f_NINSPDATE=&ec_f_INSRESULT=&ec_f_OYINSREPORTNO=&ec_f_OYNINSPDATE=&ec_f_OYINSRESULT=&ec_f_PRESOYINSREPORTNO=&ec_f_PRESNDATE=&ec_f_PRESRESULT=&ec_f_USSTATUS=&ec_f_LOGINSTATE=&ec_pg=1&ec_rd=5&1704183552765";
//		List<String> urlList = new ArrayList<>();
//		for (Company company : list) {
//			String url = StrUtil.format(template, StrUtil.split(company.getContent(), "#").get(0));
//			String resultUrl = url + "&credit=" + company.getCreditCode();
//			urlList.add(resultUrl);
//
//		}
//		List<String> urlList = Arrays.asList(template);
//
//		Spider spider = Spider.create(new GdseiPageProcessor(companyElevatorService))
//			.addPipeline(new MyPipeline(companyElevatorService));
//		for (String s : urlList) {
//			spider.addUrl(s);
//		}
//		spider.thread(25).run();


		return R.data(true);


	}

	/**
	 * 爬取海纳百川
	 */
	@GetMapping("/getHnbc")
	public void test() throws InterruptedException {
//		String url = "http://wsbj2.gdsei.org.cn:8078/seimis/jyjcWbfwHyAction.do?method=select";
//		String formData = "ec_i=ec&eti=&eti_p=&ec_efn=&ec_ev=&ec_crd=100&ec_f_a=&ec_p=1&ec_s_USEORGNAME=&ec_s_EQULOGCODE=&ec_s_USECARNO=&ec_s_EQUORGNO=&ec_s_AGENTCOMMENT=&ec_s_APPCONFMANNAME=&ec_s_PRONO=&ec_s_USSTATUS=&ec_s_ONLINELSH=&ec_s_APPNO=&ec_s_SEITESTSORT=&ec_s_EQUCLACODE=&ec_s_REPAIRAGREXTDATE=&ec_s_NINSPDATE=&ec_s_EQULOCARECOD=&ec_s_INSRESULT=&ec_s_MAIORGNAME=&1705459183135=&LOGINSTATE=1&USSTATUS=1&SYSFUNCODE=QYPT_ZZFW_DQSB&BUIORGNAME=&areacodecontent1=440000&EQUIPNAME=&areacodecontent2=&QYPT=1&1705458926456=&EQUIPMODEL=&USECARNO=&JYQKSTATE=&PRONO=&NINSPDATE_END=&STACHEORGUNICODE=&USEORGSYSNO=&EQUORGNO=&EQULOCARECOD=&USEORGNAME=%E6%B5%B7%E7%BA%B3%E7%99%BE%E5%B7%9D&EQULOGCODE=31104420002020010164&MAIORGNAME=&EQUCLACODE1=&PORGAONAME=&INSREPORTNO=&1705459154551=&1705458770060=&NINSPDATE_START=&1705458951105=&method=select&method=select&method=select&method=select&method=select&method=select&ec_totalpages=1&ec_totalrows=&ec_f_radio=&ec_f_%E5%BA%8F%E5%8F%B7=&ec_f_JYQK=&ec_f_USEORGNAME=&ec_f_EQULOGCODE=&ec_f_USECARNO=&ec_f_EQUORGNO=&ec_f_AGENTCOMMENT=&ec_f_APPCONFMANNAME=&ec_f_PRONO=&ec_f_USSTATUS=&ec_f_ONLINELSH=&ec_f_APPNO=&ec_f_SEITESTSORT=&ec_f_EQUCLACODE=&ec_f_REPAIRAGREXTDATE=&ec_f_NINSPDATE=&ec_f_EQULOCARECOD=&ec_f_INSRESULT=&ec_f_MAIORGNAME=&ec_pg=1&ec_rd=100&1705459199423";
//		url += "&" + formData;
//		List<String> urlList = Collections.singletonList(url);
//		Spider spider = Spider.create(new HnbcProcessor(companyElevatorService))
//			.addPipeline(new MyPipeline(companyElevatorService));
//		for (String s : urlList) {
//			spider.addUrl(s);
//		}
//
////		spider.runAsync();
//		spider.thread(25).run();
	}

	@GetMapping("testSoup")
	public void testSoup() {
		// 获取一次cookie
		String cookie = CookieUtil.getCookie();
		// Jsoup 解析网页
		Document doc = null;
		try {
			doc = Jsoup
				.connect("http://wsbj2.gdsei.org.cn:8078/seimis/wbglAction.do?method=wbsh&ec_i=ec&eti=&eti_p=&ec_efn=&ec_ev=&ec_crd=1000&ec_f_a=&ec_p=1&ec_s_USERORGNAME=&ec_s_SYORGANCODE=&ec_s_PARTICULARADDR=&ec_s_PROORGNAME=&ec_s_WBORGANCODE=&ec_s_WBHTBH=&ec_s_STATE=&task=view&SYSFUNCODE=QYPT_SBGL_WBSQCX&method=wbsh&checkflag=1&ec_totalpages=0&ec_totalrows=&ec_f_radio=&ec_f_%E5%BA%8F%E5%8F%B7=&ec_f_%E6%93%8D%E4%BD%9C=&ec_f_USERORGNAME=&ec_f_SYORGANCODE=&ec_f_PARTICULARADDR=&ec_f_PROORGNAME=&ec_f_WBORGANCODE=&ec_f_WBHTBH=&ec_f_STATE=&ec_pg=1&ec_rd=1000&SYDWNAME=&WBDWNAME=&HTBH=&1706587461633")
				.cookie("Cookie", cookie)
				.get();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		// <input type="button" name="edit" value="详细" onclick="do_edit('02da94a3-ce00-47b5-a36c-e9a1373d7dfa')" style="width:24" class="button_cd2>"
		// 获取所有这样的格式的onclick="do_edit('02da94a3-ce00-47b5-a36c-e9a1373d7dfa')"里的do_edit的参数
		List<String> ids = new ArrayList<>();
		doc.select("input[onclick^=do_edit]").forEach(element -> {
			String onclick = element.attr("onclick");
			String id = onclick.substring(onclick.indexOf("'") + 1, onclick.lastIndexOf("'"));
			ids.add(id);
			System.out.println(id);
		});
		System.out.println("========共分 " + ids.size() / 100 + "组执行=======");
		// 将ids 每100个分成一组
		List<List<String>> partition = Lists.partition(ids, 100);
		int count = 0;
		// 遍历每一组
		for (List<String> idList : partition) {
			for (String id : idList) {
				Document doc1 = null;
				try {
					doc1 = Jsoup
						.connect("http://wsbj2.gdsei.org.cn:8078/seimis/wbglAction.do?method=wbsh_edit&task=view&WBSQSYSID=" + id)
						.cookie("Cookie", cookie)
						.timeout(60000)
						.get();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
				// <input type="text" name="SYDWNAME" value="中山市信泓实业有限公司" readonly="readonly" id="SYDWNAME" style="width:250px">
				// 获取value 里的字段
				String companyName = doc1.select("input[name=SYDWNAME]").attr("value");
				System.out.println(companyName);
				//<input type="text" name="HTBH" value="WB2019-0613/MNT2019" readonly="readonly" style="width:170px" alt="1">
				// 获取value 里的字段
				String contractNo = doc1.select("input[name=HTBH]").attr("value");
				// <input type="text" name="EXPDATE" value="2020-06-10" style="width:70%">
				// 获取value 里的字段
				String contractTime = doc1.select("input[name=EXPDATE]").attr("value");
				/**
				 * <tr id="tr001">
				 * <td><input type="checkbox"  name="nid"  id="nid"  ></td>
				 * 												<td>1 </td>
				 * 												<td>
				 * 											曳引式客梯
				 * 												</td>
				 * 												<td>31104420002019070162 </td>
				 * 												<td>梯11粤TO5894(19) </td>
				 * 												<td>E/30047137.002 </td>
				 * 												<td>K-31789 </td>
				 * 											</tr>
				 */
				// 获取上述所有这样格式的 td, id的属性值为tr001
				Elements elements = doc1.select("tr[id^=tr]");
				// 获取所有的td
				elements.forEach(element -> {
					// 获取每个td里的所有内容
					String text = element.text();
					System.out.println(text);
					// 按逻辑分割，如果内容里也是空格，那么就算该空格也是一个值
					String[] split = StrUtil.split(text, " ").toArray(new String[0]);
					// 当长度有这么长时，再进行下一步操作
					// 获取第一个元素, 先判断下标是否越界，是：插入，否：不插入
					String elevatorType = "/";
					String elevatorNum = "/";
					String elevatorId = "/";
					String elevatorNo = "/";
					String elevatorModel = "/";
					String elevatorIdNo = "/";
					if (0 <= split.length - 1) {
						elevatorType = Func.isBlank(split[0]) ? "/" : split[0];
					}
					// 获取第二个元素
					if (1 <= split.length - 1) {
						elevatorNum = Func.isBlank(split[1]) ? "/" : split[1];
					}
					// 获取第三个元素
					if (2 <= split.length - 1) {
						elevatorId = Func.isBlank(split[2]) ? "/" : split[2];
					}
					// 获取第四个元素
					if (3 <= split.length - 1) {
						elevatorNo = Func.isBlank(split[3]) ? "/" : split[3];
					}
					// 获取第五个元素
					if (4 <= split.length - 1) {
						elevatorModel = Func.isBlank(split[4]) ? "/" : split[4];
					}
					// 获取第六个元素
					if (5 <= split.length - 1) {
						elevatorIdNo = Func.isBlank(split[5]) ? "/" : split[5];
					}
					System.out.println(elevatorType);
					System.out.println(elevatorNum);
					System.out.println(elevatorId);
					System.out.println(elevatorNo);
					System.out.println(elevatorModel);
					System.out.println(elevatorIdNo);
				});
			}
			try {
				count++;
				System.out.println("========第" + count + "组执行完毕，休息2秒=======");
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}


	}

	@GetMapping("/sendMessage")
	public void sendMessage() throws InterruptedException {
		orderScoreJob.sendPlanScoreMessage();
	}


	/**
	 * 获取单位数据
	 */
	@GetMapping("company")
	public String getCompany() {
		//获取单位数据
		String url = "http://wsbj2.gdsei.org.cn:8078/seimis/wbsearchdwAction.do?method=select&&UNITNAME=%E7%8F%A0%E6%B5%B7%E5%8D%8E%E5%8F%91%E7%89%A9%E4%B8%9A%E7%AE%A1%E7%90%86%E6%9C%8D%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%E4%B8%AD%E5%B1%B1%E5%88%86%E5%85%AC%E5%8F%B8&ORGCODE=91442000782014078Q";

		String result = HttpRequest.get(url)
			.header(Header.COOKIE, "cd_WB01625=\"\"; iswbzh=1; JSESSIONID=D27727C7F1A2D364EB65ABBACA907E4E")
			.timeout(20000)
			.execute().body();

		String content = extractData(result);
		return content;

	}

	@GetMapping("/druid")
	public void testDruid() {
		System.out.println("hello world!");
	}

	public static String extractData(String str) {
		String tagFront = "td style=\"display:none;\"  width=\"100\"   ";
		String tagEnd = "td";
		String pattern = "<" + tagFront + ">(.*?)</" + tagEnd + ">";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(str);
		if (m.find()) {
			String data = m.group(1);
			return data;
		} else {
			return "";
		}
	}

	@GetMapping("/feishu")
	@ApiOperation("飞书免登录测试")
	public R<String> feishuTest(@RequestParam String appToken, @RequestParam String tableId, @RequestParam String recordId) throws Exception {
		return R.data(feiShuUtil.getBitableRecord(appToken, tableId, recordId));
	}

	@GetMapping("/test/feishu/client")
	public R<String> testClient() throws Exception {
		String appId = "cli_a57ba002f439100c";
		String appSecret = "aRsxkv8zXF1C0FQL9V53fhnueoeZWzXO";
		Client client = Client.newBuilder(appId, appSecret).build();
		List<String> userIds = new ArrayList<>();
		userIds.add("ou_e3e7e69ad82ff92805055c23a7407f68");
		userIds.add("ou_420e6e202bbfdb537397e84c9041338a");
		userIds.add("ou_297958170dbef8b32d2b9b6615666263");
		userIds.add("ou_9bbf7deaca87ca75125e20848e6dc971");
		userIds.add("ou_267481d2b010d6df0ce643af8ae39b58");
		userIds.add("ou_d8ed4b18e1ab11005abe65f578da9daf");
		userIds.forEach(u -> {
			FeiShuCertContentTemplate feiShuCertContentTemplate = new FeiShuCertContentTemplate(appId);
			String certContentTemplate = feiShuCertContentTemplate.getCertContentTemplate();
			CreateMessageReq createMessageReq = new CreateMessageReq();
			createMessageReq.setReceiveIdType("open_id");
			CreateMessageReqBody createMessageReqBody = new CreateMessageReqBody();
			createMessageReqBody.setMsgType("interactive");
			createMessageReqBody.setReceiveId(u);
			String format = String.format(certContentTemplate, "请换证");
			createMessageReqBody.setContent(format);
			createMessageReq.setCreateMessageReqBody(createMessageReqBody);
			CreateMessageResp createMessageResp = null;
			try {
				createMessageResp = client.im().v1().message().create(createMessageReq);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		});
		return R.data("createMessageResp");
	}

	@GetMapping("/test/feishu/client/cert")
	public R<String> testCert() throws Exception {
		Client client = feiShuConfiguration.getClient(FeishuClientEnum.CERT);
		ClientSecure clitSecure = feiShuConfiguration.getClitSecure(FeishuClientEnum.CERT);
		String appId = clitSecure.getAppId();
		FeiShuCertContentTemplate feiShuCertContentTemplate = new FeiShuCertContentTemplate(appId);
		String certContentTemplateFormat = String.format(feiShuCertContentTemplate.getCertContentTemplate(), "测试换证消息");
		// 1. 获取管理员信息, 根据 OpenId 发送消息, 以下所需参数以飞书文档及工具为基准
		RawResponse resp = client.get(
			"https://open.feishu.cn/open-apis/user/v4/app_admin_user/list"
			, null
			, AccessTokenType.Tenant);
		if (resp.getStatusCode() != 200) {
			throw new RuntimeException("获取管理员信息失败");
		}
		byte[] body = resp.getBody();
		List<String> openIds = new ArrayList<>();
		// body 转换为Json
		String bodyJson = new String(body, StandardCharsets.UTF_8);
		JSONObject jsonObject = JSONObject.parseObject(bodyJson);
		JSONObject data = jsonObject.getObject("data", JSONObject.class);
		com.alibaba.fastjson.JSONArray jsonArray = data.getJSONArray("user_list");
		if (Func.isNotEmpty(jsonArray)) {
			for (Object o : jsonArray) {
				// 将 o 转换为 JSONObject
				JSONObject user = (JSONObject) o;
				String openId = user.getString("union_id");
				openIds.add(openId);
			}
		}
		if (Func.isNotEmpty(openIds)) {
			openIds.forEach(u -> {
				CreateMessageReq createMessageReq = new CreateMessageReq();
				createMessageReq.setReceiveIdType("open_id");
				CreateMessageReqBody createMessageReqBody = new CreateMessageReqBody();
				createMessageReqBody.setMsgType("interactive");
				createMessageReqBody.setReceiveId(u);
				createMessageReqBody.setContent(certContentTemplateFormat);
				createMessageReq.setCreateMessageReqBody(createMessageReqBody);
				CreateMessageResp createMessageResp = null;
				try {
					createMessageResp = client.im().v1().message().create(createMessageReq);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			});
		}
		return R.data("createMessageResp");
	}

	@GetMapping("test/feishu/client/cert/template")
	public R<String> testCertTemplate() throws Exception {
		certJob.certExpiredReminder();
		return R.data("success");
	}

	@GetMapping("test/feishu/client/cert/template/test")
	public R<List<String>> testCertTemplateTest() throws Exception {
		List<String> openIdsByDefaultParam = feiShuUtil.getOpenIdsByDefaultParam();
		return R.data(openIdsByDefaultParam);
	}

	@GetMapping("test/feishu/new/client")
	public R<List<String>> testCertTemplateTestAll() throws Exception {
		List<String> result = feiShuUtil.getOpenIdsByCustomParam();
		return R.data(result);
	}

	@Autowired
	private MessageCenterUtils messageCenterUtils;

	/**
	 * 调用成功返回：
	 * {
	 * "code": 200,
	 * "success": true,
	 * "data": [
	 * {
	 * "businessId": "b520241118162215",
	 * "messageId": "1858425472124190720",
	 * "callback": "{\"tenantId\":\"592800\",\"planId\":\"123456\"}"
	 * }
	 * ],
	 * "msg": "操作成功"
	 * }
	 */
	@PostMapping("message/center/send/")
	@ApiOperation("消息中台-发送消息测试")
	public R messageCenterSend() {
		// 模板占位符内容
		Map<String, String> contentMap = new HashMap<>(4);
		contentMap.put("min", "2");
		contentMap.put("sound", "test_10");
		contentMap.put("url", "/subpages/repair/repariDetail?planId=1860962482886676481&elevatorId=1501826743502159874");
		SendRequest request = SendRequest.builder()
			.messageTemplateId("1859411936432910337")
			.messageParam(
				MessageParam.builder()
					.receiver("1a0018970b964f519b2")
					.variables(contentMap)
					.callback(MapUtil.of("planId", "123456"))
					.build()
			).build();
		return messageCenterUtils.sendMessage(request);
	}


	@GetMapping("wx/yj/test")
	@ApiOperation("维修预警测试")
	public R testWxYj(Long planId) {
		//发送超时未达的延迟队列
		WxYjSendMsgVo wxYjSendMsgVo2 = new WxYjSendMsgVo();
		wxYjSendMsgVo2.setType(1);
		wxYjSendMsgVo2.setPlanId(planId);
		JSONObject msg = new JSONObject();
		msg.put("tenantId", AuthUtil.getTenantId());
		msg.put("contentType", MaintainPlanContentEnum.MAINTAIN_WX.getId());
		msg.put("wx_yj_msg", wxYjSendMsgVo2);
		Long s = System.currentTimeMillis() + 1 * 60000;
		mqMessageService.sendWxWarnMsg(s, JSONObject.toJSONString(msg));
		log.info("延迟队列的时间:=");
		return R.data(planId + "=" + DateUtil.format(new Date(s), "yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 测试对个人发送卡片消息
	 */
	@GetMapping("lark/card/test/personal")
	@ApiOperation("测试对个人发送卡片消息")
	public String testLarkCardPersonal() {
		// 头部模板
		LarkFaultRiskTemplateHeader headerTemplate = new LarkFaultRiskTemplateHeader();
		String header = headerTemplate.getHeader();
		String date = "2025/02/25";
		String headerFormat = String.format(header, date);
		// 主体模板
		List<RepeatFaultElevatorListDTO> paramList = new ArrayList<>();
		RepeatFaultElevatorListDTO param1 = new RepeatFaultElevatorListDTO();
		param1.setElevatorAddress("testElevatorAddress1");
		param1.setFaultRiskLevelDesc("testFaultRiskLevelDesc1");
		param1.setBuildingName("testBuildingName1");

		param1.setFaultRiskLabelDesc("testFaultRiskLabelDesc1");
		param1.setRiskWarningTime("testRiskWarningTime1");
		param1.setPlanStatusDesc("testFaultDesc1");
		param1.setExecutorMessage("testExecutorMessage1");
		param1.setRiskCloseTimeoutDesc("testRiskCloseTimeoutDesc1");
		param1.setIsScheduling("testIsScheduling1");
		RepeatFaultElevatorListDTO param2 = new RepeatFaultElevatorListDTO();
		param2.setElevatorAddress("testElevatorId2");
		param2.setBuildingName("testBuildingName2");
		param2.setFaultRiskLevelDesc("testFaultRiskLevelDesc2");
		param2.setFaultRiskLabelDesc("testFaultRiskLabelDesc2");
		param2.setRiskWarningTime("testRiskWarningTime2");
		param2.setPlanStatusDesc("testFaultDesc2");
		param2.setExecutorMessage("testExecutorMessage2");
		param2.setRiskCloseTimeoutDesc("testRiskCloseTimeoutDesc2");
		param2.setIsScheduling("testIsScheduling2");

		paramList.add(param1);
		paramList.add(param2);

		String contentBuilder = "";

		for (int i = 0; i < paramList.size(); i++) {
			RepeatFaultElevatorListDTO f = paramList.get(i);
			LarkFaultRiskTemplateMarkDownContent markDownContent = new LarkFaultRiskTemplateMarkDownContent();
			String markdown = markDownContent.getMarkdown();
			int index = i;
			String indexValue = String.valueOf(index + 1);
			String contentFormat = String.format(markdown, indexValue,
				f.getElevatorAddress(),
				f.getBuildingName(),
				f.getFaultRiskLevelDesc(),
				f.getFaultRiskLabelDesc(),
				f.getRiskWarningTime(),
				f.getPlanStatusDesc(),
				f.getExecutorMessage(),
				f.getRiskCloseTimeoutDesc(),
				f.getIsScheduling());
			contentBuilder += contentFormat;
		}

		LarkFaultRiskTemplateContent content = new LarkFaultRiskTemplateContent();
		String contentResult = content.getContent();
		contentResult = String.format(contentResult, contentBuilder);

		String finalContent = contentResult + headerFormat;

		// 测试发送对象，自己和天雄
		List<String> userIds = new ArrayList<>();
		userIds.add("59e242de");
		userIds.add("9d933gb9");
//		userIds.add("1878gea9");

		StringBuilder result = new StringBuilder();
		for (String userId : userIds) {
			result.append(feiShuUtil.sendLarkMessageByUserId(userId, finalContent));
		}
		return result.toString();
	}

	/**
	 * 测试根据等级获取飞书id
	 */
	@GetMapping("lark/get/user/id/by/level")
	@ApiOperation("测试根据等级获取飞书id")
	public R<List<String>> testGetLarkUserIdByLevel(Integer level) {
		List<String> userIds = larkFaultRiskMessageService.getLarkUserIdByLevel(level);
		return R.data(userIds);
	}

	/**
	 *
	 */
	@GetMapping("/plan/content/job")
	public R<Boolean> testPlanContentJob() {
		planContentJob.countUserByPlanOverdue();
		return R.data(Boolean.TRUE);
	}

	@GetMapping("/countByPlanSchComRisks")
	public R<Boolean> countByPlanSchComRisks() {
		planContentJob.countByPlanSchComRisks();
		return R.data(Boolean.TRUE);
	}

	@GetMapping("/xixixi")
	public R xixixi() throws Exception {
		IvrCallUtil.IvrCallRequestDto ivrCallRequestDto = new IvrCallUtil.IvrCallRequestDto();
		ivrCallRequestDto.setCalledNumber("13422801411");
		ivrCallRequestDto.setStartCode("TTS_323050041");
		ivrCallRequestDto.setTimeout(3000);
//		ivrCallRequestDto.setByeCode("ded269fe-c784-4924-b1b5-a6a5c788cfc5.wav");

		Map<String, Object> params = new HashMap<>(4);
		params.put("location", "优雅会所");
		params.put("action", "调度人员");
		ivrCallRequestDto.setStartTtsParams(params);

		List<IvrCallRequest.IvrCallRequestMenuKeyMap> list = new ArrayList<>();
		IvrCallRequest.IvrCallRequestMenuKeyMap keyMap1 = new IvrCallRequest.IvrCallRequestMenuKeyMap();
		keyMap1.setKey("1");
		keyMap1.setCode("9e20639f-7fb1-4a2a-9365-7745a91edf1a.wav");

		IvrCallRequest.IvrCallRequestMenuKeyMap keyMap2 = new IvrCallRequest.IvrCallRequestMenuKeyMap();
		keyMap2.setKey("2");
		keyMap2.setCode("TTS_323050041");
		keyMap2.setTtsParams(JSONUtil.toJsonStr(params));

		list.add(keyMap1);
		list.add(keyMap2);
		ivrCallRequestDto.setMenuKeyMap(list);

		ivrCallRequestDto.setOutId("123456789");


		IvrCallResponse response = ivrCallUtil.initiateIvrCall(ivrCallRequestDto);
		return R.data(response);
	}

	@Resource
	private ApplicationEventPublisher applicationEventPublisher;

	@GetMapping("/test/alarm/notice")
	@Transactional(rollbackFor = Exception.class)
	public R testAlarmNotice() {
		// 消息通知
		applicationEventPublisher.publishEvent(new NoticeEvent(NoticeTaskParam.builder()
			.businessType(BusinessType.RESCUE.getCode())
			.triggerNode(TriggerNodeEnum.CREATE.getCode())
			.triggerCondition(TriggerConditionEnum.CONDITION_19.getCode())
			.bizId(1954776217313411074L)
			.tenantId("592800")
			.build()
		));
		return R.success("发送成功");
	}

	@GetMapping("testAlarmLabel")
	public R testAlarmLabel() {
		JSONObject send = new JSONObject();
		send.put("planId", 1954795601551212546L);
		send.put("bType", RescueArriveEnum.OVERTIME_NOT_DISPATCH.getId());
		send.put("overtimeNotDispatch", 1);
		mqMessageService.sendRescueArrive(DateUtil.offsetMinute(DateUtil.date(), 1).getTime(), send.toJSONString());
		return R.success("发送成功");
	}

	@GetMapping("/galaxyRepairPlanDetailJobV2")
	public R<Boolean> galaxyRepairPlanDetailJobV2() {
		larkRescueAndFaultIndexJob.galaxyRepairPlanCountJobV2();
		larkRescueAndFaultIndexJob.galaxyRescuePlanCountJobV2();
		return R.data(Boolean.TRUE);
	}
}
